package com.socket1;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;

import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Client {

    public static void main(String[] args) {
        try {
            // 与指定地址, 指定端口建立连接
            Socket socket = new Socket("127.0.0.1", 55511);
            Console.log("socket is connected success: {}", socket.getLocalPort());

            // 拿到输入输出流
            InputStream in = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(in);
            OutputStream out = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);

            for (int i = 0; i < 1; i++) {
                String msg = "push a msg " + i;
                byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
                // 使用一个buffer,将数据头和数据体结合成一个包发送
                ByteBuffer buffer = ByteBuffer.allocate(bytes.length + 1);
                buffer.put((byte) bytes.length);
                buffer.put(bytes);
                // 根据协议, 先一个字节的数据头, 再写数据体
                dataOutputStream.write(buffer.array());
                dataOutputStream.flush();

                // 发送完消息, 服务端会给一个反馈, 也是按照协议的格式来的
                int len = dataInputStream.readByte();
                byte[] bytes1 = new byte[len];
                dataInputStream.read(bytes1);
                String answer = new String(bytes1, CharsetUtil.CHARSET_UTF_8);
                Console.log("server answer msg:{}", answer);
            }
            System.out.println("client closing");
            socket.shutdownOutput();
            socket.shutdownInput();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
